import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { localCache } from '@/utils/storage'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
	easing: 'ease',
	speed: 500,
	showSpinner: false,
	trickleSpeed: 200,
	minimum: 0.3
})

const routes: RouteRecordRaw[] = [
	{
		path: '/',
		redirect: '/main'
	},
	{
		name: 'login',
		path: '/login',
		meta: {
			title: '登录'
		},
		component: () => import('@/layout/login')
	},
	{
		name: 'main',
		path: '/main',
		redirect: '/index',
		component: () => import('@/layout/main.vue'),
		children: [
			{
				name: 'index',
				path: '/index',
				meta: { title: '首页' },
				component: () => import('@/views/index.vue')
			}
		]
	},
	{
		path: '/:pathMatch(.*)*',
		name: 'notFound',
		meta: {
			title: '后台管理-404'
		},
		component: () => import('@/layout/not-found/not-found.vue')
	}
]

const router = createRouter({
	history: createWebHistory(),
	routes
})

router.beforeEach((to) => {
	NProgress.start()

	if (to.path !== '/login') {
		const token = localCache.getItem('token')
		if (!token) {
			return '/login'
		}
	}
})

router.afterEach((to) => {
	NProgress.done()
	if (to.meta.title) {
		document.title = `后台管理-${to.meta.title}`
	}
})

export default router
